package com.android.cattlefarm;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.cattlefarm.db.AddDB;
import com.android.cattlefarm.db.ImportDB;
import com.android.cattlefarm.util.Constants;
import com.android.cattlefarm.util.ExportEntity;
import com.android.cattlefarm.util.FileEntity;
import com.android.cattlefarm.util.FileUtil;
import com.android.cattlefarm.util.ImportEntity;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

/**
 * Created by Huang on 2015/7/4.
 */
public class ImportActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    public static String ROOT_FILE_PATH = "/mnt/sdcard/" + Constants.FILE_ROOT;
    public static String ROOT_FILE_PARENT_PATH = "/mnt/sdcard";
    private ListView mListView;
    private List<FileEntity> filesList = new ArrayList<>();
    private FileAdapter fileAdapter;
    private String fileParentPath;
    private String currentPath;
    private String selectFilePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_import);
        mListView = (ListView) findViewById(R.id.import_list);
        mListView.setOnItemClickListener(this);
        setCurrentFile(ROOT_FILE_PATH);
    }

    private void setCurrentFile(String path) {
        filesList.clear();
        File file = new File(path);
        currentPath = path;
        fileParentPath = file.getParentFile().getAbsolutePath();
        if (file.isDirectory()) {
            File flist[] = file.listFiles();
            for (int i = 0; i < flist.length; i++) {
                File currentFile = flist[i];
                FileEntity fileEntity = new FileEntity();
                fileEntity.setPath(currentFile.getAbsolutePath());
                fileEntity.setName(currentFile.getName());
                fileEntity.setModifyTime(currentFile.lastModified());
                if (currentFile.isDirectory()) {
                    fileEntity.setIsDirectory(true);
                    try {
                        fileEntity.setFileCount(currentFile.listFiles().length);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                filesList.add(fileEntity);
            }
        }
        fileAdapter = new FileAdapter(this, filesList);
        mListView.setAdapter(fileAdapter);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        FileEntity fileEntity = (FileEntity) mListView.getAdapter().getItem(position);
        if (fileEntity == null) return;

        if (fileEntity.isDirectory())
            setCurrentFile(fileEntity.getPath());
        else {
            if (fileEntity.getName().endsWith("xls")) {
                selectFilePath = fileEntity.getPath();
                AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom));
                builder.setTitle("是否导入这个文件?");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        importFile();
                    }
                });
                builder.setNegativeButton("取消", null);
                builder.setNeutralButton("打开文件", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        FileUtil.openFile(ImportActivity.this, selectFilePath);
                    }
                });
                builder.create().show();

            }
        }
    }

    private void importFile() {
        showLoading();
        List<ExportEntity> infoList = getInfoList(selectFilePath);
        if (infoList.size() > 0) {
            AddDB importDB = new AddDB(this);
            long i = importDB.insertImport(infoList);
            if (i > 0) showMessage("导入成功");
            else showMessage("导入失败,请重试");
            importDB.closeDataBase();
        } else {
            showMessage("导入失败,请确认文件格式为xls");
        }
        hideLoading();
    }

    public void backClick(View v) {
        if (fileParentPath != null && !fileParentPath.equals(ROOT_FILE_PARENT_PATH)) {
            setCurrentFile(fileParentPath);
        } else {
            finish();
        }
    }

    private List<ExportEntity> getInfoList(String filePath) {
        List<ExportEntity> info = new ArrayList<>();
        try {
            Workbook book = Workbook.getWorkbook(new File(filePath));
            Sheet sheet = book.getSheet(0);
            int row = sheet.getRows();
            int columns = sheet.getColumns();
            if (columns >= 9)
                for (int i = 1; i < row; i++) {
                    ExportEntity importEntity = new ExportEntity();
                    if (sheet.getRow(i).length > 0 &&sheet.getRow(i)[0] != null && sheet.getRow(i)[0].getContents() != null)
                        importEntity.setCowNum(sheet.getRow(i)[0].getContents());
                    if (sheet.getRow(i).length > 3 &&sheet.getRow(i)[3] != null && sheet.getRow(i)[3].getContents() != null)
                        importEntity.setBirthday(sheet.getRow(i)[3].getContents());
                    if (sheet.getRow(i).length > 2 &&sheet.getRow(i)[2] != null && sheet.getRow(i)[2].getContents() != null)
                        importEntity.setCowfarmName(sheet.getRow(i)[2].getContents());
                    if (sheet.getRow(i).length > 1 &&sheet.getRow(i)[1] != null && sheet.getRow(i)[1].getContents() != null)
                        importEntity.setCowfarmNum(sheet.getRow(i)[1].getContents());
                    if (sheet.getRow(i).length > 6 && sheet.getRow(i)[6] != null && sheet.getRow(i)[6].getContents() != null)
                        importEntity.setFather(sheet.getRow(i)[6].getContents());
                    if (sheet.getRow(i).length > 8 &&sheet.getRow(i)[8] != null && sheet.getRow(i)[8].getContents() != null)
                        importEntity.setGrandfather(sheet.getRow(i)[8].getContents());
                    if (sheet.getRow(i).length > 7 &&sheet.getRow(i)[7] != null && sheet.getRow(i)[7].getContents() != null)
                        importEntity.setMother(sheet.getRow(i)[7].getContents());
                    if (sheet.getRow(i).length > 5 &&sheet.getRow(i)[5] != null && sheet.getRow(i)[5].getContents() != null)
                        importEntity.setProductionTime(sheet.getRow(i)[5].getContents());
                    if (sheet.getRow(i).length > 4 &&sheet.getRow(i)[4] != null && sheet.getRow(i)[4].getContents() != null)
                        importEntity.setTyre(sheet.getRow(i)[4].getContents());
                    info.add(importEntity);
                }
        } catch (BiffException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return info;
    }

    private void showMessage(String str) {
        Toast toast = new Toast(this);
        View toastView = LayoutInflater.from(this).inflate(R.layout.toast_text, null);
        TextView textView = (TextView) toastView.findViewById(R.id.toast_text);
        textView.setText(str);
        toast.setView(toastView);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 10);
        toast.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (fileParentPath != null && !fileParentPath.equals(ROOT_FILE_PARENT_PATH)) {
                setCurrentFile(fileParentPath);
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


}